package com.mls.fivedistrict.server.impl;

import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.dao.SysSettingMapper;
import com.mls.fivedistrict.pojo.SysSetting;
import com.mls.fivedistrict.pojo.SysSettingExample;
import com.mls.fivedistrict.server.SysSettingService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by chenxiuxiang on 2018/3/15.
 */
@Service("sysSettingService")
public class SysSettingServiceImpl implements SysSettingService {
    @Resource(name = "sysSettingMapper")
    SysSettingMapper sysSettingMapper;

    @Override
    public ServiceResponse addSysSetting(SysSetting sysSetting) {
        int row = sysSettingMapper.insert(sysSetting);
        if (row > 0) {
            return ServiceResponse.createSuccessResponse();
        }
        return ServiceResponse.createErrorResponse();
    }

    @Override
    public ServiceResponse editSysSetting(SysSetting sysSetting) {
        int row = sysSettingMapper.updateByPrimaryKeySelective(sysSetting);
        if (row > 0) {
            return ServiceResponse.createSuccessResponse();
        }
        return ServiceResponse.createErrorResponse();
    }

    @Override
    public ServiceResponse getSysSettings() {
        List<SysSetting> data = sysSettingMapper.getAllSysSetting();
        Map<String, String> maps = data.stream().collect(Collectors.toMap(SysSetting::getSettingKey, SysSetting::getSettingValue));
        return ServiceResponse.createSuccessResponse(maps);
    }

    @Override
    public ServiceResponse getSysSetting(Long id) {
        SysSetting setting = sysSettingMapper.selectByPrimaryKey(id);
        return ServiceResponse.createSuccessResponse(setting);
    }

    @Override
    public ServiceResponse getSysSettingList() {
        List<SysSetting> sysSettings = sysSettingMapper.getAllSysSetting();
        return ServiceResponse.createSuccessResponse(sysSettings);
    }

    @Override
    public ServiceResponse updateSettings(Map<String, String> params) {
        int row = sysSettingMapper.updateSettings(params);
        if (row > 0) {
            return ServiceResponse.createSuccessResponse();
        }
        return ServiceResponse.createErrorResponse();
    }

    @Override
    public SysSetting getSysSettingByKey(String skey) {
        SysSettingExample sysSettingExample = new SysSettingExample();
        SysSettingExample.Criteria criteria = sysSettingExample.createCriteria();
        criteria.andSettingKeyEqualTo(skey);
        List<SysSetting> sysSettingList = sysSettingMapper.selectByExample(sysSettingExample);
        if (sysSettingList == null || sysSettingList.size() == 0) {
            return null;
        }
        return sysSettingList.get(0);
    }
}
